package apis

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	. "hais.pw/shorturl/models"
	utlis "hais.pw/shorturl/utils"
)

//添加 Link
func LinkAddApi(c *gin.Context) {
	link := new(Link)
	err := c.Bind(link)
	utlis.PrintError(err)
	if link.Address == "" {
		c.JSON(http.StatusOK, utlis.HTTP_ERROR_503("目标地址不能为空！"))
	} else if !utlis.IsURL(link.Address) {
		c.JSON(http.StatusOK, utlis.HTTP_ERROR_503("请填写正确的目标地址！"))
	} else if utlis.IsTNumber(link.Address) {
		c.JSON(http.StatusOK, utlis.HTTP_ERROR_503("标签不能是 T+数字"))
	} else if err := link.Add(); err != nil {
		c.JSON(http.StatusOK, utlis.HTTP_ERROR_503("请检测标签是否重复"))
	} else {
		link.NewUrl = fmt.Sprintf("http://%s/%s", c.Request.Host, link.Short)
		c.JSON(http.StatusOK, utlis.HTTP_SUCCESS(link))
	}
}

//跳转到首页
func GoToHome(c *gin.Context) {
	c.Redirect(302, "http://d.myk.pw") //重定向跳转
}

//根据 标签 跳转
func LinkToByShort(c *gin.Context) {
	link := new(Link)
	link.Short = c.Param("tag")
	if findErr := link.FindByShort(); findErr != nil {
		c.JSON(http.StatusOK, utlis.HTTP_ERROR_404(findErr))
	} else {
		link.Click++
		link.Save()
		c.Redirect(302, link.Address) //重定向跳转
	}
}

//根据 标签 查询 Link
func LinkFindByShort(c *gin.Context) {
	link := new(Link)
	link.Short = c.Param("short")
	if findErr := link.FindByShort(); findErr != nil {
		c.JSON(http.StatusOK, utlis.HTTP_ERROR_404(findErr))
	} else {
		link.NewUrl = fmt.Sprintf("http://%s/%s", c.Request.Host, link.Short)
		c.JSON(http.StatusOK, utlis.HTTP_SUCCESS(link))
	}
}
